<?php
namespace App\Helper;

use App\Lib\Consul\Service;
use Swoft\Bean\Annotation\Mapping\Bean;

/**
 * Class ServiceHelper 用来选取服务
 * @package App\Helper
 * @Bean()
 */
class ServiceHelper
{

    /**
     * 当前索引
     * @var int
     */
    private $index = 0;

    /**
     * 随机算法
     * @param array $services
     * @return Service
     */
    public function random(array $services):Service {
        if(empty($services)) return new Service([]);
        $index = array_rand($services, 1);
        return new Service($services[$index]);
    }

    /**
     * 轮询算法
     * @param array $services
     * @return Service
     */
    public function roundRobin(array $services):Service {
        if(empty($services)) return new Service([]);
        $service_num = count($services);
        $this->index = ++$this->index % $service_num;
        return new Service($services[$this->index]);
    }

    /**
     * ipHash 算法
     * @param array $services
     * @return Service
     */
    public function ipHash(array $services):Service {
        if(empty($services)) return new Service([]);
        $service_num = count($services);
        $ip = ip();
        $index = crc32($ip) % $service_num;
        return new Service($services[$index]);
    }

}
